<template>
  <div class="compre-page-container">
    <el-card>
      <template #header>
        <span>综合管理</span>
      </template>
      
      <el-tabs v-model="activeTab" class="management-tabs">
        <!-- 奖学金管理标签页 -->
        <el-tab-pane label="奖学金管理" name="scholarship">
          <div class="scholarship-management-content">
            <!-- 奖学金类型配置 -->
            <div class="config-section">
              <h3 class="section-title">奖学金类型配置</h3>
              <el-card shadow="never" class="config-card">
                <div class="toolbar">
                  <el-button type="primary" @click="handleAddType">
                    <el-icon><Plus /></el-icon>
                    添加类型
                  </el-button>
                </div>
                <el-table :data="scholarshipTypes" stripe style="width: 100%" class="config-table">
                  <el-table-column prop="name" label="奖学金名称" width="200" align="left" />
                  <el-table-column prop="code" label="类型代码" width="120" align="left" />
                  <el-table-column prop="amount" label="金额（元）" width="150" align="left">
                    <template #default="{ row }">
                      <span class="amount-text">¥{{ row.amount }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="描述" min-width="200" align="left" show-overflow-tooltip />
                  <el-table-column prop="status" label="状态" width="100" align="center">
                    <template #default="{ row }">
                      <el-tag :type="row.status === '启用' ? 'success' : 'info'" size="small">
                        {{ row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template #default="{ row }">
                      <el-button type="primary" size="small" link @click="handleEditType(row)">
                        编辑
                      </el-button>
                      <el-button type="danger" size="small" link @click="handleDeleteType(row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>

            <!-- 申请条件配置 -->
            <div class="config-section">
              <h3 class="section-title">申请条件配置</h3>
              <el-card shadow="never" class="config-card">
                <el-form :model="conditionConfig" label-width="150px" class="condition-form">
                  <el-form-item label="最低GPA要求">
                    <el-input-number
                      v-model="conditionConfig.minGPA"
                      :min="0"
                      :max="4.0"
                      :step="0.1"
                      :precision="2"
                      style="width: 200px"
                    />
                    <span class="form-tip">（满分4.0）</span>
                  </el-form-item>
                  <el-form-item label="违纪记录限制">
                    <el-radio-group v-model="conditionConfig.allowDiscipline">
                      <el-radio :label="true">允许有违纪记录</el-radio>
                      <el-radio :label="false">不允许有违纪记录</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="申请时间范围">
                    <el-date-picker
                      v-model="conditionConfig.applyDateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 300px"
                    />
                  </el-form-item>
                  <el-form-item label="是否需要申请材料">
                    <el-switch v-model="conditionConfig.requireMaterials" />
                  </el-form-item>
                  <el-form-item label="申请材料清单" v-if="conditionConfig.requireMaterials">
                    <el-checkbox-group v-model="conditionConfig.materials">
                      <el-checkbox label="成绩单">成绩单</el-checkbox>
                      <el-checkbox label="推荐信">推荐信</el-checkbox>
                      <el-checkbox label="个人陈述">个人陈述</el-checkbox>
                      <el-checkbox label="获奖证书">获奖证书</el-checkbox>
                      <el-checkbox label="其他材料">其他材料</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSaveCondition">保存配置</el-button>
                    <el-button @click="handleResetCondition">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <!-- 审批流程配置 -->
            <div class="config-section">
              <h3 class="section-title">审批流程配置</h3>
              <el-card shadow="never" class="config-card">
                <el-form :model="approvalConfig" label-width="150px" class="condition-form">
                  <el-form-item label="审批流程">
                    <el-steps :active="approvalConfig.steps.length - 1" finish-status="success" align-center>
                      <el-step
                        v-for="(step, index) in approvalConfig.steps"
                        :key="index"
                        :title="step.title"
                        :description="step.description"
                      />
                    </el-steps>
                  </el-form-item>
                  <el-form-item label="是否需要多级审批">
                    <el-switch v-model="approvalConfig.multiLevel" />
                  </el-form-item>
                  <el-form-item label="审批级别" v-if="approvalConfig.multiLevel">
                    <el-select v-model="approvalConfig.approvalLevel" placeholder="请选择审批级别" style="width: 200px">
                      <el-option label="一级审批（辅导员）" value="counselor" />
                      <el-option label="二级审批（学院）" value="college" />
                      <el-option label="三级审批（学校）" value="school" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="审批时限（天）">
                    <el-input-number
                      v-model="approvalConfig.timeLimit"
                      :min="1"
                      :max="30"
                      style="width: 200px"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSaveApproval">保存配置</el-button>
                    <el-button @click="handleResetApproval">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <!-- 奖学金申请列表 -->
            <div class="config-section">
              <h3 class="section-title">奖学金申请管理</h3>
              <el-card shadow="never" class="config-card">
                <div class="toolbar">
                  <el-row :gutter="16">
                    <el-col :span="8">
                      <el-input
                        v-model="applicationSearchForm.keyword"
                        placeholder="请输入学号或姓名搜索"
                        clearable
                        @clear="handleApplicationSearch"
                        @keyup.enter="handleApplicationSearch"
                      >
                        <template #prefix>
                          <el-icon><Search /></el-icon>
                        </template>
                        <template #append>
                          <el-button @click="handleApplicationSearch">查询</el-button>
                        </template>
                      </el-input>
                    </el-col>
                    <el-col :span="6">
                      <el-select v-model="applicationSearchForm.status" placeholder="申请状态" clearable @change="handleApplicationSearch">
                        <el-option label="待审核" value="pending" />
                        <el-option label="已通过" value="approved" />
                        <el-option label="已拒绝" value="rejected" />
                      </el-select>
                    </el-col>
                    <el-col :span="6">
                      <el-select v-model="applicationSearchForm.type" placeholder="奖学金类型" clearable @change="handleApplicationSearch">
                        <el-option
                          v-for="type in scholarshipTypes"
                          :key="type.code"
                          :label="type.name"
                          :value="type.code"
                        />
                      </el-select>
                    </el-col>
                  </el-row>
                </div>
                <el-table :data="applicationList" stripe style="width: 100%" class="config-table">
                  <el-table-column prop="studentNum" label="学号" width="140" align="left" />
                  <el-table-column prop="name" label="姓名" width="120" align="left" />
                  <el-table-column prop="scholarshipType" label="奖学金类型" width="150" align="left" />
                  <el-table-column prop="gpa" label="GPA" width="100" align="center" />
                  <el-table-column prop="disciplineStatus" label="违纪情况" width="120" align="center">
                    <template #default="{ row }">
                      <el-tag :type="row.disciplineStatus === '无' ? 'success' : 'danger'" size="small">
                        {{ row.disciplineStatus }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="申请状态" width="120" align="center">
                    <template #default="{ row }">
                      <el-tag :type="getApplicationStatusType(row.status)" size="small">
                        {{ getApplicationStatusName(row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="applyTime" label="申请时间" width="180" align="left" />
                  <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template #default="{ row }">
                      <el-button
                        v-if="row.status === 'pending'"
                        type="success"
                        size="small"
                        @click="handleApproveApplication(row)"
                      >
                        通过
                      </el-button>
                      <el-button
                        v-if="row.status === 'pending'"
                        type="danger"
                        size="small"
                        @click="handleRejectApplication(row)"
                      >
                        拒绝
                      </el-button>
                      <el-button type="primary" size="small" link @click="handleViewApplication(row)">
                        详情
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pagination-section">
                  <el-pagination
                    v-model:current-page="applicationPagination.currentPage"
                    v-model:page-size="applicationPagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="applicationPagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleApplicationSizeChange"
                    @current-change="handleApplicationPageChange"
                  />
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑奖学金类型对话框 -->
    <el-dialog
      v-model="typeDialogVisible"
      :title="typeDialogTitle"
      width="600px"
      @close="handleTypeDialogClose"
    >
      <el-form
        ref="typeFormRef"
        :model="typeForm"
        :rules="typeRules"
        label-width="120px"
      >
        <el-form-item label="奖学金名称" prop="name">
          <el-input v-model="typeForm.name" placeholder="请输入奖学金名称" />
        </el-form-item>
        <el-form-item label="类型代码" prop="code">
          <el-input v-model="typeForm.code" placeholder="请输入类型代码（如：NATIONAL_LEVEL_1）" />
        </el-form-item>
        <el-form-item label="金额（元）" prop="amount">
          <el-input-number
            v-model="typeForm.amount"
            :min="0"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="typeForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入奖学金描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="typeForm.status" placeholder="请选择状态" style="width: 200px">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="typeDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmitType">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 申请详情对话框 -->
    <el-dialog
      v-model="applicationDetailDialogVisible"
      title="申请详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ currentApplicationDetail.studentNum }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentApplicationDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="奖学金类型">{{ currentApplicationDetail.scholarshipType }}</el-descriptions-item>
        <el-descriptions-item label="申请金额">¥{{ currentApplicationDetail.amount }}</el-descriptions-item>
        <el-descriptions-item label="GPA">{{ currentApplicationDetail.gpa }}</el-descriptions-item>
        <el-descriptions-item label="违纪情况">
          <el-tag :type="currentApplicationDetail.disciplineStatus === '无' ? 'success' : 'danger'" size="small">
            {{ currentApplicationDetail.disciplineStatus }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag :type="getApplicationStatusType(currentApplicationDetail.status)" size="small">
            {{ getApplicationStatusName(currentApplicationDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentApplicationDetail.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="申请理由" :span="2">{{ currentApplicationDetail.reason || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentApplicationDetail.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="applicationDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

const activeTab = ref('scholarship')
const typeDialogVisible = ref(false)
const applicationDetailDialogVisible = ref(false)
const typeDialogTitle = ref('添加奖学金类型')
const submitLoading = ref(false)
const typeFormRef = ref<FormInstance>()

// 奖学金类型列表
const scholarshipTypes = ref([
  {
    id: 1,
    name: '国家奖学金',
    code: 'NATIONAL_LEVEL_1',
    amount: 8000,
    description: '国家设立的优秀学生奖学金，面向成绩优异的学生',
    status: '启用'
  },
  {
    id: 2,
    name: '国家励志奖学金',
    code: 'NATIONAL_LEVEL_2',
    amount: 5000,
    description: '国家设立的面向家庭经济困难学生的奖学金',
    status: '启用'
  },
  {
    id: 3,
    name: '校级奖学金',
    code: 'SCHOOL_LEVEL_1',
    amount: 3000,
    description: '学校设立的优秀学生奖学金',
    status: '启用'
  }
])

// 申请条件配置
const conditionConfig = reactive({
  minGPA: 3.0,
  allowDiscipline: false,
  applyDateRange: null,
  requireMaterials: true,
  materials: ['成绩单', '推荐信']
})

// 审批流程配置
const approvalConfig = reactive({
  multiLevel: true,
  approvalLevel: 'college',
  timeLimit: 7,
  steps: [
    { title: '提交申请', description: '学生提交申请材料' },
    { title: '辅导员审核', description: '辅导员初步审核' },
    { title: '学院审核', description: '学院审批' },
    { title: '学校审核', description: '学校最终审批' }
  ]
})

// 申请搜索表单
const applicationSearchForm = reactive({
  keyword: '',
  status: '',
  type: ''
})

// 申请列表数据
const applicationList = ref([
  {
    id: 1,
    studentNum: '2024001',
    name: '张三',
    scholarshipType: '国家奖学金',
    gpa: 3.8,
    disciplineStatus: '无',
    status: 'pending',
    applyTime: '2024-01-15 10:00:00'
  },
  {
    id: 2,
    studentNum: '2024002',
    name: '李四',
    scholarshipType: '国家励志奖学金',
    gpa: 3.5,
    disciplineStatus: '无',
    status: 'approved',
    applyTime: '2024-01-14 10:00:00'
  }
])

// 申请分页
const applicationPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 奖学金类型表单
const typeForm = reactive({
  id: null,
  name: '',
  code: '',
  amount: 0,
  description: '',
  status: '启用'
})

// 类型表单验证规则
const typeRules: FormRules = {
  name: [
    { required: true, message: '请输入奖学金名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入类型代码', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '金额必须大于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 当前申请详情
const currentApplicationDetail = reactive({
  studentNum: '',
  name: '',
  scholarshipType: '',
  amount: 0,
  gpa: 0,
  disciplineStatus: '',
  status: '',
  applyTime: '',
  reason: '',
  remark: ''
})

// 添加类型
const handleAddType = () => {
  typeDialogTitle.value = '添加奖学金类型'
  typeForm.id = null
  typeForm.name = ''
  typeForm.code = ''
  typeForm.amount = 0
  typeForm.description = ''
  typeForm.status = '启用'
  typeDialogVisible.value = true
}

// 编辑类型
const handleEditType = (row: any) => {
  typeDialogTitle.value = '编辑奖学金类型'
  typeForm.id = row.id
  typeForm.name = row.name
  typeForm.code = row.code
  typeForm.amount = row.amount
  typeForm.description = row.description
  typeForm.status = row.status
  typeDialogVisible.value = true
}

// 删除类型
const handleDeleteType = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除奖学金类型 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
  } catch {
    // 用户取消
  }
}

// 提交类型表单
const handleSubmitType = async () => {
  if (!typeFormRef.value) return
  
  await typeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // TODO: 调用添加/编辑接口
        await new Promise(resolve => setTimeout(resolve, 500))
        ElMessage.success(typeForm.id ? '编辑成功' : '添加成功')
        typeDialogVisible.value = false
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 关闭类型对话框
const handleTypeDialogClose = () => {
  typeFormRef.value?.resetFields()
}

// 保存申请条件配置
const handleSaveCondition = async () => {
  try {
    // TODO: 调用保存接口
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('申请条件配置保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 重置申请条件配置
const handleResetCondition = () => {
  ElMessageBox.confirm('确定要重置申请条件配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    conditionConfig.minGPA = 3.0
    conditionConfig.allowDiscipline = false
    conditionConfig.applyDateRange = null
    conditionConfig.requireMaterials = true
    conditionConfig.materials = ['成绩单', '推荐信']
    ElMessage.success('已重置')
  }).catch(() => {
    // 用户取消
  })
}

// 保存审批流程配置
const handleSaveApproval = async () => {
  try {
    // TODO: 调用保存接口
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('审批流程配置保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 重置审批流程配置
const handleResetApproval = () => {
  ElMessageBox.confirm('确定要重置审批流程配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    approvalConfig.multiLevel = true
    approvalConfig.approvalLevel = 'college'
    approvalConfig.timeLimit = 7
    ElMessage.success('已重置')
  }).catch(() => {
    // 用户取消
  })
}

// 申请搜索
const handleApplicationSearch = () => {
  // TODO: 实现搜索逻辑
  ElMessage.info('搜索功能开发中...')
}

// 获取申请状态类型
const getApplicationStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || ''
}

// 获取申请状态名称
const getApplicationStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 通过申请
const handleApproveApplication = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要通过该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    // TODO: 调用审核通过接口
    row.status = 'approved'
    ElMessage.success('审核通过')
  } catch {
    // 用户取消
  }
}

// 拒绝申请
const handleRejectApplication = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要拒绝该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用审核拒绝接口
    row.status = 'rejected'
    ElMessage.success('已拒绝')
  } catch {
    // 用户取消
  }
}

// 查看申请详情
const handleViewApplication = (row: any) => {
  Object.assign(currentApplicationDetail, {
    ...row,
    amount: scholarshipTypes.value.find(t => t.name === row.scholarshipType)?.amount || 0,
    reason: '该生学习成绩优异，符合申请条件',
    remark: ''
  })
  applicationDetailDialogVisible.value = true
}

// 申请分页
const handleApplicationSizeChange = (size: number) => {
  applicationPagination.pageSize = size
  // TODO: 重新加载数据
}

const handleApplicationPageChange = (page: number) => {
  applicationPagination.currentPage = page
  // TODO: 重新加载数据
}
</script>

<style scoped>
.compre-page-container {
  padding: 0;
}

.management-tabs {
  margin-top: 20px;
}

.scholarship-management-content {
  padding: 20px 0;
}

.config-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.config-card {
  margin-top: 16px;
}

.toolbar {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.config-table {
  margin-top: 20px;
}

.amount-text {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.condition-form {
  padding: 20px 0;
}

.form-tip {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
